﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;

namespace BSS.OAuth2.Facebook
{
    public class AuthenticationProvider: IOAuthProvider
    {
        string _facebookApplicationId;
        string _faceobokSecret;

        public AuthenticationProvider(string facebookApplicationId, string facebookSecret)
        {
            _facebookApplicationId = facebookApplicationId;
            _faceobokSecret = facebookSecret;
        }

        #region IOAuthProvider Members

        public string GetAuthorizationCodeRequestUrl(string redirectUrl, string scopeCollection)
        {
            return string.Format("https://www.facebook.com/dialog/oauth?client_id={1}&redirect_uri={0}&scope={2}", redirectUrl, _facebookApplicationId, scopeCollection);
        }

        public string GetAccessToken(string authorizationCode, string redirectUrl)
        {
            string requestUrl = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", _facebookApplicationId, redirectUrl, _faceobokSecret, authorizationCode);
            WebRequest request = WebRequest.Create(requestUrl);
            var response = request.GetResponse();
            var stream = response.GetResponseStream();
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            StreamReader reader = new StreamReader(stream, encode);
            string result = reader.ReadToEnd().Replace("access_token=", "");
            reader.Close();
            response.Close();
            return result;
        }

        public IUser GetUser(string accessToken)
        {
            string url = string.Format("https://graph.facebook.com/me?access_token={0}", accessToken);
            var serializer = new DataContractJsonSerializer(typeof(FacebookUser));

            var request = WebRequest.Create(url);
            var response = request.GetResponse();
            var stream = response.GetResponseStream();

            var user = new FacebookUser();
            user = serializer.ReadObject(stream) as FacebookUser;

            response.Close();
            return user;
        }

        #endregion

    }
}
